<?php
class SongsController extends AppController {

	var $name = 'Songs';
	public $components = array('Comments.Comments' => array('userModelClass' => 'Users.User'));
	
	function beforeFilter(){
		parent::beforeFilter();
		$this->passedArgs['comment_view_type'] = 'threaded';
		$allowed_actions=array('index','view','add','topRandom');
		if (!in_array($this->action,$allowed_actions)){
			$this->redirect(array('controller' => 'songs', 'action' => 'index'));
		}
		$this->Auth->allow('index','view', 'topRandom');
	}

	function index() {
		$this->Song->recursive = 0;
		$this->paginate = array('order' => 'Song.score/(now()- Song.date) DESC', 'limit' => '20');
		$songs = $this->paginate(); 
		foreach ($songs as $id=>$song){
			$songs[$id]['Sitemask']['embedurl'] = preg_replace('/__url__/',$song['Song']['url_for_embed'],$song['Sitemask']['embedurl']);
		}
		$this->set('songs', $songs);

		//loading scores for user
		$this->loadModel('Score');
		$conditions = array("Score.user_id" => $this->Auth->user('id'));
		$scores = $this->Score->find('all', array('conditions' => $conditions));
		$this->set('scores', $scores);
		App::Import('Model', 'Group'); 
		$this->Group = new Group; 
		$groups = $this->Group->find('all', array('order'=>array('Group.title asc')));
		$categories = $this->Song->Category->find('all',array('order'=>array('Category.title asc')));

		//for rss
		$channel = array('title' => 'AUDIVIT | List of all new Songs',
			'link' => '/songs',
			'description' => 'Recent song posts.',
			'language' => 'en-us',
		);
		$this->set(compact('categories', 'groups','channel'));
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid song', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('song', $this->Song->read(null, $id));

		//loading scores for user
		$this->loadModel('Score');
		$conditions = array("Score.user_id" => $this->Auth->user('id'));
		$scores = $this->Score->find('all', array('conditions' => $conditions));

		$conditions = array("Song.id" => $id);
		$this->paginate = array('order' => 'Song.score/(now()- Song.date) DESC', 'limit' => '20','conditions'=> $conditions);
		$songs = $this->paginate();
		foreach ($songs as $i=>$song){
			$songs[$i]['Sitemask']['embedurl'] = preg_replace('/__url__/',$song['Song']['url_for_embed'],$song['Sitemask']['embedurl']);
		}

		$this->set( 'songs', $songs); 
		$this->set('scores', $scores);
		App::Import('Model', 'Group'); 
		$this->Group = new Group; 
		$groups = $this->Group->find('all', array('order'=>array('Group.title asc')));
		$categories = $this->Song->Category->find('all',array('order'=>array('Category.title asc')));
		$this->set(compact('categories', 'groups'));
	}

	function add() {
		if (!empty($this->data)) {
			$sitemasks = ClassRegistry::init('Sitemask')->find('all');
			foreach ($sitemasks as $sitemask=>$sm){
				if(preg_match_all($sm['Sitemask']['mask'],$this->data['Song']['url'],$results)){
					$this->data['Song']['sitemask_id']=$sm['Sitemask']['id'];
					$this->data['Song']['url_for_embed']=$results[3][0];
				}
			}
			$this->data['Song']['url'] = preg_replace('/http:\/\//','',$this->data['Song']['url']);
			$this->data['Song']['user_id']=$this->Auth->user('id');
			$this->data['Song']['date']= null;
			$this->Song->create();
			if ($this->Song->save($this->data)) {
				ClassRegistry::init('Discussion')->create();
				$this->data['Discussion']['date']=null;
				ClassRegistry::init('Discussion')->save($this->data);
				$this->data['Song']['discussion_id']=ClassRegistry::init('Discussion')->getLastInsertID();
				$this->edit($this->Song->getLastInsertID());
				$this->Session->setFlash(__('The song has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The song could not be saved. Please, try again.', true));
			}
		}
		App::Import('Model', 'Group'); 
		$this->Group = new Group; 
		$groups = $this->Group->find('all', array('order'=>array('Group.title asc')));
		$discussions = $this->Song->Discussion->find('list');
		$categories = $this->Song->Category->find('all',array('order'=>array('Category.title asc')));
		$users = $this->Song->User->find('list');
		$this->set(compact('discussions', 'categories', 'users', 'groups'));
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid song', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Song->save($this->data)) {
				$this->Session->setFlash(__('The song has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The song could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Song->read(null, $id);
		}
		$discussions = $this->Song->Discussion->find('list');
		$categories = $this->Song->Category->find('list');
		$users = $this->Song->User->find('list');
		$this->set(compact('discussions', 'categories', 'users'));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for song', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Song->delete($id)) {
			$this->Session->setFlash(__('Song deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Song was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
	function topRandom(){
		$songs= $this->Song->query('select *  from users User, songs Song,categories Category where Song.category_id=Category.id and Song.user_id=User.id and (Song.score/(now()- Song.date)) = (select max(score/(now()- date)) from songs where category_id=Category.id)');
		$songs = array($songs[array_rand($songs)]);

		//for rss
		$channel = array('title' => 'AUDIVIT | The most popular song for a category as on today',
			'link' => '/',
			'description' => 'At AUDIVIT you can vote up or down to decide most popular song for the next days.',
			'language' => 'en-us');
		$this->set(compact('songs','channel'));

	}
}
